function SMSEngineSunrise(theUsername,thePassword) {


var innerSessionID = -1;
var remainningSMS = -1;
var username = theUsername;
var password = thePassword;
var innerSMSCount=0;
var isJustAuthenticated = false;

//Since the AppleWebToolkit do not allow to set cookie
//we are using a home made implementation of the XMLHttpRequest
var xmlRequest = new SimpleHTTPRequest();// XMLHttpRequest();


var smsChars = 130;

this.getAvailSMS = function () {
	if(innerSessionID == -1)
		doAuthentication(null,null);
	else
		loadSMS();
};


this.Send = function (smsText,number) {
	sendSMS(smsText,number);
};


this.GetSMSCharsCount = function () {
	return smsChars;
};

this.getSMSCount = function () {
	return remainningSMS;
};

this.isConnected = function () {
	return innerSessionID != -1;
};


this.isSMSCountCritical = function () {
	return (innerSMSCount < 10);
};

this.isSMSCountWarning = function () {
	return (innerSMSCount < 25);
};

this.hasEnoughCredits = function (messLenght) {
	return (messLenght <= smsChars * innerSMSCount);	
};

//The main function, only this function has to be calles

function sendSMS(smsText,number){
	
	if(smsText==null)
		return loadSMS(null,null);
	
	//Partition mess in multiple sms
	var queue_mess=new Array();
	while(smsText.length>smsChars){
		queue_mess.push(smsText.substring(0,smsChars));
		smsText=smsText.substring(smsChars, smsText.length);
	}
	queue_mess.push(smsText);
		
	sendSingleSMS(queue_mess,number);
}



function sendSingleSMS(queue_mess,number){

	engineStatusFeedBack("Sending");
		
	var mess = queue_mess[queue_mess.length-1]; //Mess to send

	var feedURL = "http://mymobile.sunrise.ch/portal/res/member/;jsessionid="+innerSessionID+"?_DARGS=/portal/sunrise/sms/html/standard_sms.jsp";
	
	var onloadHandler = function() {responseHandler(xmlRequest,queue_mess,number,false,true); };
	//xmlRequest = new XMLHttpRequest();
	xmlRequest.onload = onloadHandler;
	xmlRequest.open("POST",feedURL,true);
	//xmlRequest.setRequestHeader("Cookie", "jsessionid="+innerSessionID);
	
	var postData = "_dyncharset=iso-8859-1";


	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.orgNumber")+"="+"msisdn";
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.orgNumber")+"=+";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.successUrl")+"="+URLEncode("/portal/res/member/;jsessionid="+innerSessionID);
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.successUrl")+"=+";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.destination")+"="+URLEncode(number);
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.destination")+"=+";
    postData +="&"+URLEncode("_D:MESSAGE")+"=+";              
	postData +="&"+URLEncode("MESSAGE")+"="+URLEncode(mess);				 
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update.x")+"=10";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update.y")+"=30";
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update")+"=+";			 
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.sendMessages")+"=true";
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.sendMessages")+"=+";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.formName")+"=SmsSend";			
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.formName")+"=+";						    
	postData +="&"+URLEncode("_DARGS")+"="+URLEncode("/portal/sunrise/sms/html/standard_sms.jsp");	
	
	xmlRequest.send(postData);
}

function doAuthentication(queue_mess,number) 
{
	isJustAuthenticated=true;
	
	engineStatusFeedBack("Logging");
	
	//var feedURL = "http://mymobile.sunrise.ch/portal/res/guest;jsessionid="+innerSessionID;
	var feedURL = "http://mymobile.sunrise.ch/portal/res/guest;jsessionid=-1"
	var onloadHandler = function() { responseHandler(xmlRequest,queue_mess,number,true,false); };
	var xmlRequest = new XMLHttpRequest();
	xmlRequest.onload = onloadHandler;
	xmlRequest.open("POST",feedURL,true);
	
	var postData = "_dyncharset=iso-8859-1";


	postData +="&"+"_lg="+URLEncode(username);
	postData +="&"+URLEncode("_D:_lg")+"=+";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/login/LoginFormHandler.value.password")+"="+URLEncode(password);
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.value.password")+"=+";
	postData +="&"+URLEncode("/ch/sunrise/portal/mobile/login/LoginFormHandler.mysuccessUrl")+"="+URLEncode("/portal/res/member/;jsessionid="+innerSessionID+"?oblngch=it_CH");     
	postData +="&"+URLEncode("_D:/ch/sunrise/portal/mobile/login/LoginFormHandler.mysuccessUrl")+"=+";
	postData +="&"+"loginSubmitImage.x=13&loginSubmitImage.x=19";                                
	postData +="&"+URLEncode("_D:loginSubmitImage")+"=";
	postData +="&"+URLEncode("_DARGS")+"="+URLEncode("/portal/sunrise/login/html/LargeLogin.jsp");
               
	xmlRequest.setRequestHeader("Cache-Control", "no-cache");
	xmlRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	xmlRequest.send(postData);

}



function loadSMS(queue_mess,number){

	engineStatusFeedBack("Updating");
	
	var feedURL = "";
	//var xmlRequest = new XMLHttpRequest();
	//if(innerSessionID==-1)
	//	feedURL = "http://mymobile.sunrise.ch/portal/res/guest?paf_dm=full&paf_gm=content&paf_gear_id=100001";
	//else{
		//feedURL = "http://mymobile.sunrise.ch/portal/res/member/web;jsessionid="+innerSessionID;
		feedURL = "http://mymobile.sunrise.ch/portal/res/member/web";
		//xmlRequest.setRequestHeader("Cookie", "jsessionid="+innerSessionID);	
	//}
		
	var onloadHandler = function() { responseHandler(xmlRequest,queue_mess,number,false,false); };
	
	xmlRequest.onload = onloadHandler;
	xmlRequest.open("GET",feedURL,true);
	xmlRequest.send(null);
}


//----------------------------------------------------------------------------------
// Single Respones Handler
//----------------------------------------------------------------------------------

function responseHandler(xmlRequest,queue_mess,number,withAutentication,withSendSMS){
	
	
	if (xmlRequest.status != 200) {
		alert("Error fetching session id data: HTTP status " + xmlRequest.status);
		return engineFeedBack("ConnectionError");
	}
	
	
	if(getIsLogedIn(xmlRequest.responseText)){
		innerSessionID=1;
	}else{
		innerSessionID=-1;
		if(withAutentication){ //In case we are doing the autentication do not check the session
			alert("Unable to log in!");
			return engineFeedBack("LogError");
		}else{
			if(isJustAuthenticated){
				alert("Unable to set cookies!");
				return engineFeedBack("CookieError");
			}else{
				return doAuthentication(queue_mess,number);
			}
		}
	}
	
	isJustAuthenticated = false;
	
	
	// Retreive remaining SMS
	remainningSMS= getSMSCount(xmlRequest.responseText);
	if (remainningSMS == -1) {
			alert("Unable to retreive remaining sms");
			return engineFeedBack("SMSCountError");
	}

	
	if(queue_mess == null) //There is no sms to send it was a simply login
		return engineFeedBack("LogOK");
	
	//If a sms was sent check it
	if(withSendSMS && !getSMSisSent(xmlRequest.responseText)){
		alert("Unable to send sms!");
		return engineFeedBack("SMSError");
	}
	
	//If we are here is because we have sent an sms
	queue_mess.pop(); //If no error happens remove the sent message from the queue
	
	//If there is other sms to send send it;
	if(queue_mess.length){
		return setTimeout(sendTimeOutedSingleSMS, 2000);
	}

	//This function exist to create a local scope for the setTimeout call
	function sendTimeOutedSingleSMS(){
		return sendSingleSMS(queue_mess,number);
	}

	//There is no sms to send
	return engineFeedBack("SMSOK");

}


//----------------------------------------------------------------------------------
// Check Functions
//----------------------------------------------------------------------------------

function getSMSisSent(html){
	
	//Check if the page contains contents that you obtain when login is successfull		
	if (html.indexOf("SMS mandato") == -1) {
			return false;
	}

	return true;
}

function getIsLogedIn(html){
		
	//Check if the page contains contents that you obtain when login is successfull
	//should be to make better!!		
	if (html.indexOf("navigationborder_left") == -1) {
			return false;
	}

	return true;
}



function getSMSCount(html){
		
	var smsDetecStr1 = "_D:/ch/sunrise/portal/mobile/sms/SmsSendFormHandler.update";
	var smsDetecStr2 = "TD align=\"right\">";
	
	if (html.indexOf(smsDetecStr1) == -1) {
		alert("Unable to retreive session id!");
		return-1;
	}
	
	var begin  = html.indexOf(smsDetecStr1) + smsDetecStr1.length;
		begin  = html.indexOf(smsDetecStr2,begin) + smsDetecStr2.length;
		
	var end = html.indexOf("&nbsp;gratis",begin);
	
	if (end - begin  > 200 || end - begin  < 0) {
		alert("Unable to retreive remaining free sms from html!");
		return 0;
	}
	
	var gratisSMS = html.substring(begin, end).trim();
	
	begin  = html.indexOf("<br>",end) + "<br>".length;
	end = html.indexOf("&nbsp;pagati",begin);
	
	if (end - begin  > 200 || end - begin  < 0) {
		alert("Unable to retreive remaining payed sms from html!");
		return gratisSMS;
	}
	
	var payedSMS = html.substring(begin, end).trim();
	
	innerSMSCount = parseInt(gratisSMS)+parseInt(payedSMS);
	
	return parseInt(gratisSMS)+parseInt(payedSMS) + " SMS left";
}

}
